package com.ivan.stu.notetool.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.zackratos.ultimatebar.UltimateBar;
import com.ivan.stu.notetool.R;
import com.ivan.stu.notetool.adapter.NoteAdapter;
import com.ivan.stu.notetool.callback.ItemClickListener;
import com.ivan.stu.notetool.model.NoteBean;
import com.ivan.stu.notetool.model.NotifyFinishEvent;
import com.ivan.stu.notetool.network.api.SafeApiManager;
import com.ivan.stu.notetool.network.intercepter.NetworkTransformer;
import com.ivan.stu.notetool.network.postbody.NoteInfoPostBody;
import com.ivan.stu.notetool.network.response.ApiResponse;
import com.ivan.stu.notetool.network.response.NoteResponse;
import com.ivan.stu.notetool.utils.ActivityCollectorUtils;
import com.ivan.stu.notetool.utils.ConstrantManager;
import com.ivan.stu.notetool.utils.HtmlUtil;
import com.ivan.stu.notetool.utils.StringUtil;
import com.ivan.stu.notetool.utils.TextViewUtils;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


import io.reactivex.observers.ResourceObserver;

public class SearchNoteActivity extends AppCompatActivity implements View.OnClickListener{

    private ImageView iv_left_back,iv_search_close;
    private EditText ed_search;
    private TextView tv_search;
    private List<NoteBean> noteBeans = new ArrayList<>();
 //   private SearchNoteAdapter mAdapter;

    private NoteAdapter mAdapter;
    private RecyclerView mRecyclerView;
    private Handler mHandler = new Handler();
    private ImageView iv_empty,iv_clear_text;
    private TextView tv_empty;
    private RelativeLayout rl_search;
    private String mCurrentSysID = "";
    private String mCurrentSysName = "";
    private String keyword = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_search_note);
        UltimateBar.Companion.with(this).applyNavigation(false).create().transparentBar();
        if (!EventBus.getDefault().isRegistered(this)) {

            EventBus.getDefault().register(this);

        }
        findViews();

   //     ActivityCollectorUtils.addActivity(this);

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFinishEvent(NotifyFinishEvent event){

        if (event.getFinishSigin() == 0 || event.getFinishSigin() == 1){

            finish();

        }


    }



    private void findViews() {

        iv_empty = findViewById(R.id.iv_empty);
        tv_empty = findViewById(R.id.tv_empty);
        rl_search  = findViewById(R.id.rl_search);
        iv_clear_text = findViewById(R.id.iv_clear_search);
        iv_left_back = (ImageView) findViewById(R.id.iv_left_back);
        ed_search = (EditText) findViewById(R.id.ed_search);
        iv_search_close = (ImageView) findViewById(R.id.iv_clear_search);
        tv_search = (TextView) findViewById(R.id.tv_search);
        mRecyclerView = findViewById(R.id.recyclerView);


        iv_left_back.setOnClickListener(this);
        tv_search.setOnClickListener(this);
        iv_clear_text.setOnClickListener(this);
        rl_search.setOnClickListener(this);

        mAdapter = new NoteAdapter(SearchNoteActivity.this,noteBeans);
        mAdapter.setmCurrentSysName(mCurrentSysName);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(SearchNoteActivity.this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setItemClickListener(new ItemClickListener(){
            @Override
            public void onItemClick(int positon, View itemView) {

                //点击进入编辑界面
                Intent intent = new Intent(SearchNoteActivity.this,EditNoteActivity.class);
                intent.putExtra("NoteBean",noteBeans.get(positon));
                intent.putExtra("IsFromSearch",true);
                startActivity(intent);

            }

            @Override
            public void onItemLongClick(int position, View itemView) {

            }
        });


        setEditTextInputSpace(ed_search);
        ed_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                handleInputString(charSequence.toString());

            }

            @Override
            public void afterTextChanged(Editable editable) {

                if (!editable.toString().equals("")){

                    iv_clear_text.setVisibility(View.VISIBLE);

                }else {

                    iv_clear_text.setVisibility(View.INVISIBLE);
                }

                handleInputString(editable.toString());

            }
        });

        iv_empty.setVisibility(View.VISIBLE);
        tv_empty.setVisibility(View.VISIBLE);
        mRecyclerView.setVisibility(View.GONE);
    }



    private void handleInputString(String input) {

        if (!input.equals("")){

            keyword = input;

        }else {

            keyword = "";

            iv_empty.setVisibility(View.VISIBLE);
            tv_empty.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);

        }
    }

    private void getNoteList(String sysID, String subjectID, final String keyCon){

        NoteInfoPostBody body = new NoteInfoPostBody();
        body.setBackUpOne("");
        body.setBackUpTwo("");
        body.setSecretKey("");
        body.setEndTime("");
        body.setStartTime("");
        body.setIsKeyPoint(-1);
        body.setKeycon(keyCon);
        body.setPage(0);
        body.setSize(0);
        body.setSubjectID(subjectID);
        body.setSysID(sysID);
        body.setUserID(ConstrantManager.childUserID);
        body.setUserType(ConstrantManager.userType);
        body.setNoteID("");
        body.setResourceID(ConstrantManager.currentResourceID);
        body.setMaterialID(ConstrantManager.MaterialID);

        SafeApiManager.getTestApi(3).getNoteList(body)
                .compose(NetworkTransformer.<ApiResponse<NoteResponse>>commonSchedulers())
                .subscribe(new ResourceObserver<ApiResponse<NoteResponse>>() {
                    @Override
                    public void onNext(ApiResponse<NoteResponse> noteResponseApiResponse) {

                        noteBeans.clear();
                        noteBeans = noteResponseApiResponse.Result.NoteList;
                        //进行noteList的重构

                        //先获得时间列表
                        //再将时间列表中的重复项去除
                        //使用双重for循环构造新的数据列表。

                        if (noteBeans!=null && noteBeans.size()>0){

                            mAdapter.setKeyWord(keyCon);

                            //     ArrayList<NoteBean> dataList = getDataList(noteBeans);

                            List<NoteBean> dataList = noteBeans;

                            for (int i=0;i<dataList.size();i++){   //去除笔记中的图片路径

                                NoteBean noteBean = dataList.get(i);
                                noteBean.setNormal(true);
                                if (noteBean.isNormal()){
                                    String noteContent =   noteBean.getNoteContent();
                                    ArrayList<String> imageUrls = HtmlUtil.getImageSrcFromText(noteContent);
                                    if (imageUrls!=null && imageUrls.size()>0){
                                        noteBean.setImageUrls(imageUrls);
                                    }
                                }
                            }


                            Log.e("最终拿到的数据",dataList.size()+"");


                            mAdapter.removeAllItemFromDataList();
                            final Context context = mRecyclerView.getContext();
                            final LayoutAnimationController controller =
                                    AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_fall_down);
                            mRecyclerView.setLayoutAnimation(controller);
                            mAdapter.addAll(dataList);
                            mRecyclerView.scheduleLayoutAnimation();


                            iv_empty.setVisibility(View.GONE);
                            tv_empty.setVisibility(View.GONE);
                            mRecyclerView.setVisibility(View.VISIBLE);


                        }else {

                            iv_empty.setVisibility(View.VISIBLE);
                            tv_empty.setVisibility(View.VISIBLE);
                            mRecyclerView.setVisibility(View.GONE);

                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                        TextViewUtils.showToast(SearchNoteActivity.this,0,e.toString());
                        iv_empty.setVisibility(View.VISIBLE);
                        tv_empty.setVisibility(View.VISIBLE);
                        mRecyclerView.setVisibility(View.GONE);

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }



    public static void setEditTextInputSpace(EditText editText) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" ") || source.toString().contentEquals("\n")) {
                    return "";
                } else {
                    return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    @Override
    public void onClick(View view) {

        int i = view.getId();
        if (i == R.id.iv_left_back) {
            hideSystemKeyBoard();
            finish();

        } else if (i == R.id.tv_search) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    hideSystemKeyBoard();
                    if (!keyword.equals("")) {

                        getNoteList(ConstrantManager.currentSystemid, ConstrantManager.currentNoteSubjectID, keyword);  //系统id和学科id是由集成的系统决定

                    } else {

                        TextViewUtils.showToast(SearchNoteActivity.this, 1, "请输入搜索关键字！");
                    }

                }
            }, 0);

        } else if (i == R.id.iv_clear_search) {
            ed_search.setText("");

            iv_clear_text.setVisibility(View.INVISIBLE);

        } else if (i == R.id.rl_search) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    opeSystemKeyBoard();
                    ed_search.requestFocus();

                }
            }, 0);

        } else {
        }

    }


    public void opeSystemKeyBoard() {
        InputMethodManager imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(this.getCurrentFocus(),
                InputMethodManager.SHOW_FORCED);

    }

    public void hideSystemKeyBoard(){

        InputMethodManager imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(tv_search.getWindowToken(), 0); //强制隐藏键盘
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
